#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# TwiTalker - Tweet it easy with your GTalk
# Copyright 2009-2010 Kavin Gray
# See LICENSE for details.
# 
#

import re
import base64
import httplib, urllib,urllib2
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.api import xmpp
from apptwitter import AppEngineTwitter
from db_service import DBService
import config

DATABASE={1:"TwiDbA",2:"TwiDbB",3:"TwiDbC",4:"TwiDbD",5:"TwiDbE",6:"TwiDbF",7:"TwiDbG",8:"TwiDbH",9:"TwiDbI",10:"TwiDbJ"}
UNBINDING_MSG="对不起，你还没有通过认证来进行绑定，请访问 http://twitalker.appspot.com/ 获取认证码和密钥，\
并按以下格式输入进行认证绑定: *-v 空格 认证码 空格 密钥*\n有其他疑问请访问: http://twitalker.appspot.com/faq:\n\n"


class TService():

    def __init__(self):

        self.oauth_key =  config.OAUTH_KEY                                  # app oauth_key
        self.oauth_secret = config.OAUTH_SECRET                             # app oauth_secret
        self.bot_acount=  config.ACCOUNT                                    # bot account
        self._results = None                                                # result for the querying user


    def isCommand(self,msg):
        '''
        Check for Commands
        Command => Retrun True
        Not a command => Return False
        '''
        if(len(msg)<=1):
            if(msg=='-'):
                return True
            else:
                return False
        elif(msg.lower()=='help' or (msg[0]=='-' and msg[1]<>'-')):
            return True
        else:
            return False


    def parseCommand(self,msg,add):
        '''
        Check and execute command
        Account unbinded => Retrun UNBINDING_MSG
        Invalid command  => Retrun ERROR Msg
        Command => Execute funciton and return the respon
        '''
        command=msg.lower()
        param=command.split(' ')
        db_ser=DBService(add)
        
        # check if the gtalk user have already binded to the account
        if(not db_ser.isUser()):           
            # command to bind to a new account
            if(len(param)==3 and param[0]=='-v'):
                return self.setOauth(msg.split(' ')[1],msg.split(' ')[2],add)
            
            return UNBINDING_MSG

        self._results=db_ser.getQuery()        
        # Proccess and execute the commands      
        if(command=='-help' or command=='-h' or command=='help' or command=='-?'):
            return self.getHelp() 
        elif(command=='-all'):
            return self.getCommands() 
        elif(command=='-tool'):
            return self.getTool()
        elif(command=='-on'):
            return self.setMode('on')
        elif(command=='-self'):
            return self.setMode('self')
        elif(command=='-live'):
            return self.setMode('live')
        elif(command=='-off'):
            return self.setMode('off')
        elif(command=='-idon'):
            return self.setMode('idon')
        elif(command=='-idoff'):
            return self.setMode('idoff')
        elif(command=='-status' or command=='-st'):
            return self.getStatus()
        elif(command=='-@'):
            return self.getMention() 
        elif(command=='-d'):
            return self.getDM()
        elif(command=='-r' or command=='-rt'):
            return self.getRT()
        elif(command=='-fav'):
            return self.getFav()
        elif(command=='-me'):
            return self.getTL()
        elif(command=='-home' or command=='-ho'):
            return self.getHomeTL()
        elif(command=='-del'):
            return self.delMsg()
        elif(command=='-mlist' or command=='-mt'):
            return self.getIList()
        elif(command=='-list' or command=='-lt'):
            return self.getList()
        elif(command=='-listed' or command=='-ld'):
            return self.getListed()
        elif(command=='-remove'):
            return self.removeUser()
        elif(command=='-update'):
            return self.updateUser()
        # command which have a arg
        elif(len(param)==2):
            if(param[0]=='-rt'):
                if(param[1].isdigit()):
                    return self.setRT(param[1])
                else:
                    return self.getRT(param[1])
            elif(param[0]=='-r'):
                if(param[1].isdigit()):
                    return self.setNewRT(param[1])
                else:
                    return self.getRT(param[1])
            elif(param[0]=='-del'):
                return self.delMsg(param[1])
            elif(param[0]=='-status' or param[0]=='-st'):
                return self.getStatus(param[1])
            elif(param[0]=='-@'):
                return self.getMention(param[1]) 
            elif(param[0]=='-d'):
                return self.getDM(param[1])
            elif(param[0]=='-fav'):
                if(param[1].isdigit()):
                    return self.setFav(param[1])
                else:
                    return self.getFav(param[1])
            elif(param[0]=='-me'):
                return self.getTL(param[1])
            elif(param[0]=='-home' or param[0]=='-ho'):
                return self.getHomeTL(param[1])
            elif(param[0]=='-follow' or param[0]=='-fo'):
                return self.setFollow(param[1])
            elif(param[0]=='-unfollow' or param[0]=='-uf' or param[0]=='-unfo'):
                return self.setUnFollow(param[1])
            elif(param[0]=='-if'):
                return self.isFollow(param[1])
            elif(param[0]=='-msg'):
                return self.getMsg(param[1])
            elif(param[0]=='-time' or param[0]=='-t'):
                return self.setTime(param[1])
            elif(param[0]=='-mlist' or param[0]=='-mt'):
                return self.getIList(param[1])
            elif(param[0]=='-list' or param[0]=='-lt'):
                return self.getList(param[1])
            elif(param[0]=='-listed' or param[0]=='-ld'):
                return self.getListed(param[1])
        # command which have two arg
        elif(len(param)>=3):
            if(param[0]=='-@'):
                return self.setReply(param[1],msg)
            elif(param[0]=='-d'):
                return self.setDM(msg.split(' ')[1],msg)
            elif(param[0]=='-rt' or param[0]=='-r'):
                return self.setRT(param[1],msg)
            elif(param[0]=='-live'):
                return self.setMode('live',param[1],param[2])
            elif(param[0]=='-list'):
                if(len(param)==3):
                    return self.getListTL(param[1],param[2])
                else:
                    return self.getListTL(param[1],param[2],param[3])
            elif(param[0]=='-v'):
                return self.updateOauth(msg.split(' ')[1],msg.split(' ')[2])
            
        return '对不起，你输入的命令有误，请检查下命令格式是否正确，输入-help查看帮助'
            




    # =======================================================================
    #
    #           Methods to proccess and execute the commands 
    #
    # =======================================================================




    def getHelp(self):
        '''
        Command: -help/-h
        Return help lists
        '''
        return '''欢迎使用TwiTalker，\
如果您是第一次使用请先访问 http://twitalker.appspot.com/ 进行认证，\
下面是TwiTalker的部分常见命令，输入-all查看所有命令\n\n\
●  *发推：直接发送140字以内的消息即可*\n\
●  绑定用户：-v 空格 认证码 空格 密钥\n\
●  开启完全消息接收(接收好友消息和私信)：-on\n\
●  开启自我消息接收(只接受@我消息和私信)：-self\n\
●  完全关闭消息接收(屏蔽所有消息)：-off\n\
●  直播模式消息接收(接收默认群组消息)：-live\n\
●  给某人发送私信：-d 空格 用户名 空格 私信内容\n\
●  *回复某人：@用户名  空格 内容*\n\
●  关注某人：-follow 空格 用户名 或 -fo 空格 用户名\n\
●  取消关注某人: -unfollow 空格 用户名 或 -uf 空格 用户名\n\
●  开启消息附加ID模式：-idon\n\
●  关闭消息附加ID模式：-idoff\n\
●  *查看更多命令：-all*\n\n\
更多详细信息及建议欢迎Follow官方帐号Twi_Talker( https://twitter.com/twi_talker )，祝您使用愉快 ^ ^''' 


    def getCommands(self):
        '''
        Command: -all
        List all the commands of twitalker
        '''
        return '''\
TwiTalker所有命令：\n\n\
●  *发推：直接发送140字以内的消息即可*\n\
●  绑定用户：-v 空格 认证码 空格 密钥\n\
●  删除绑定：-remove\n\
●  个人TwiTalker信息：-status 或 -st\n\
●  附加工具：-tool\n\n\
●  开启完全消息接收(接收好友消息和私信)：-on\n\
●  开启自我消息接收(只接受@我消息和私信)：-self\n\
●  完全关闭消息接收(屏蔽所有消息)：-off\n\
●  *直播模式消息接收(接收默认群组消息)：-live*\n\
●  *设置直播模式默认群组：-live 群组创建者用户名 群组名或群组ID号* _(例:-live kavin_gray test)_\n\
●  设置消息接收刷新时间：-time 空格 分钟数 _(只能取1到5的整数)_\n\n\
●  查看收藏：-fav 页数 _(页数可省略，页数之前要带字母P，如-fav p2)_\n\
●  查看私信：-d 页数 _(页数可省略，页数之前要带字母P，如-d p2)_\n\
●  @我消息：-@ 页数 _(页数可省略，页数之前要带字母P，如-@ p2)_\n\
●  好友RT消息：-rt 页数 _(页数可省略，页数之前要带字母P，如-rt p2)_\n\
●  自己发表的消息：-me 页数 _(页数可省略，页数之前要带字母P，如-me p2)_\n\
●  最近好友更新：-home 页数 或 -ho 页数 _(页数可省略，页数之前要带字母P，如-ho p2)_\n\
●  查看群组更新：-list 群组创建者 群组名或群组ID 页数 或 -lt 群组创建者 群组名或群组ID 页数 _(页数可省略，页数之前要带字母P)_\n\n\
●  你创建的群组：-mlist next/pre 或 -mt next/pre _(next或pre可省略，如需翻页则用next或pre分别表示下页或上页)_\n\
●  你关注的群组：-list next/pre 或 -lt next/pre _(next或pre可省略，如需翻页则用next或pre分别表示下页或上页)_\n\
●  关注你的群组：-listed next/pre 或 -ld next/pre _(next或pre可省略，如需翻页则用next或pre分别表示下页或上页)_\n\n\
●  *回复某人：@用户名  空格 内容*\n\
●  回复特定消息：-@ 空格 消息id号 空格 回复内容\n\
●  查看特定消息：-msg 空格 消息id号\n\
●  删除最近发布的一条消息：-del\n\
●  删除自己的消息：-del 空格 消息id号\n\
●  给某人发送私信：-d 空格 用户名 空格 私信内容\n\
●  消息收藏：-fav 空格 消息id号\n\
●  消息RT：-rt 空格 消息id号 空格 附加消息(附加消息可省略)\n\
●  官方RT：-r 空格 消息id号\n\n\
●  查看某人信息：-status 空格 用户名 或 -st 空格 用户名\n\
●  关注某人：-follow 空格 用户名 或 -fo 空格 用户名\n\
●  取消关注某人: -unfollow 空格 用户名 或 -uf 空格 用户名\n\
●  某人是否关注你: -if 空格 用户\n\n\
●  开启消息附加ID模式：-idon\n\
●  关闭消息附加ID模式：-idoff\n\n'''


    def getTool(self):
        '''
        Command: -tool
        List all the commands of twitalker
        '''
        return '''\
TwiTalker工具箱\n\n\
●  TwiTalker FAQ：http://twitalker.appspot.com/faq \n\n\
●  短网址还原：http://longurl.org/expand\n\n\
●  图片上传：http://www.mobypicture.com\n\n'''   



    def setMode(self,mode,name='',list='0'):
        '''
        Command: -on/-off/-self/-live/-live name list/-idon/-idoff
        Set the mode for receiving tweets 
        '''
        db_ser = DBService()
        
        for user in self._results:
            
            if(mode==user.mode and name==''):
                return '您的接收状态已经是'+mode+'模式了\n\n'
            
            if(mode=='on'):
                db_ser.setMode(user,'on')
                return '设置成功！完全消息接收已打开，将自动接收好友消息和私信:)\n\n'
                
            elif(mode=='self'):
                db_ser.setMode(user,'self')
                return '设置成功！自我消息接收已打开，将只接收好友@我消息和私信:)\n\n'
                
            elif(mode=='live'):
                # -live
                if(list=='0'):
                    if(user.list=='null' or user.list==''):
                        return '您还未设置默认群组，请输入 *-live 群组创建者用户名 群组名或群组ID* 设置默认群组\n\n'
                    else:
                        db_ser.setMode(user,'live')
                        return '设置成功！Live模式已打开，将接收群组'+user.list.replace('/lists/',':').encode('utf-8')+'的消息:)\n\n'
                # -live name list        
                else:
                    actoken=user.actoken
                    actokense=user.actokense
                    tww = AppEngineTwitter()
                    tww.set_oauth(self.oauth_key,
                            self.oauth_secret,
                            actoken,
                            actokense)
                    try:
                        statecode=tww.getListInfo(name,list)
                    except:
                        statecode=400
                    if(statecode==200):
                        live=name+'/lists/'+str(list)
                        db_ser.setMode(user,'live',live)
                        return '设置成功！Live模式已打开，将接收群组'+live.replace('/lists/',':').encode('utf-8')+'的消息:)\n\n'
                    else:
                        return '设置失败，可能小组不存在或被设为私密状态，请检查格式及用户群组名是否正确，稍后再试\n\n'
                        
            elif(mode=='off'):
                db_ser.setMode(user,'off')
                return '设置成功！完全消息接收已关闭，将屏蔽所有消息:)\n\n'
                
            elif(mode=='idon'):
                db_ser.setMode(user,'idon')
                return '设置成功！消息附加ID模式已打开:)\n\n'
                
            elif(mode=='idoff'):
                db_ser.setMode(user,'idoff')
                return '设置成功！消息附加ID模式已关闭:)\n\n'



    def getStatus(self,name=''):
        '''
        Command: -status/-st/-status name/-st name 
        Return the status of the user
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            
            for times in range(retry):
                try:
                    if(name==''):
                        statecode=tww.getUserInfo(user.name.encode("utf-8"))
                    else:
                        statecode=tww.getUserInfo(name.encode("utf-8"))
                    if(statecode==200):
                        break
                except:
                    pass
                
            if(statecode==404):
                return '操作失败，无此用户，请检查用户名是否正确，稍后再试\n\n'
            
            elif(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

            # parsing info for users           
            content = simplejson.loads(tww.getContent())
            respon="用户个人信息\n\n"
            respon=respon+"用户名： "+content['screen_name'].encode("utf-8")+"\n\n"
            respon=respon+"昵称： "+content['name'].encode("utf-8")+"\n\n"
            respon=respon+"所在地:  "+content['location'].encode("utf-8")+"\n\n"
            respon=respon+"消息数:  "+str(content['statuses_count'])+"\n\n"
            respon=respon+"好友数:  "+str(content['friends_count'])+"\n\n"
            respon=respon+"关注者:  "+str(content['followers_count'])+"\n\n"
            respon=respon+"个人介绍:  "+content['description'].encode("utf-8")+"\n\n"
            respon=respon+"最近更新:  "+content['status']['text'].encode("utf-8")+"\n\n"
            
            # -st/-status.show more info
            if(name==''):
                respon=respon+"消息接受模式:  "
                if(user.mode=='self'):
                    respon=respon+"-self （自我消息接收模式）"
                elif(user.mode=='on'):
                    respon=respon+"-on （完全消息接收模式）"
                elif(user.mode=='off'):
                    respon=respon+"-off （完全消息屏蔽模式）"
                else:
                    respon=respon+"-live （Live接收模式，默认群组:"+user.list.replace('/lists/',':').encode("utf-8")+")"
                respon=respon+"\n\n消息自动刷新时间:  "+str(user.settime)+"分钟"                                
                respon=respon+"\n\n附加ID模式:  "
                if(user.rt==True):
                    respon=respon+"开启状态"
                else:
                    respon=respon+"关闭状态"
                    
                respon=respon+"\n\n"
            
        return respon


    
    def getMention(self,page='p0'):
        '''
        Command: -@/-@ page
        Return tweets from mentions timeline.
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-@ p1以查看指定页回复\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.mentions(0,pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'ment',user) # get tweets
            if(respon<>''):
                if(pg==0):
                    respon='最近收到的回复： \n\n'+respon
                else:
                    respon='你的回复 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oops..没有收到的回复\n\n'
                
            return respon



    def getDM(self,page='p0'):
        '''
        Command: -d/-d page
        Return the direct messages.
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-d p1以查看指定页私信\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getDMessage(0,pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
            
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'dm',user)
            if(respon<>''):
                if(pg==0):
                    respon='最近收到的私信： \n\n'+respon
                else:
                    respon='收到的私信 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop..没有收到的私信\n\n'
                    
            return respon




    def getFav(self,page='p0'):
        '''
        Command: -fav/-fav page
        Return the timeline of ur favorite tweets
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-fav p1以查看指定页收藏\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getFav(pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
            
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'fav',user)
            if(respon<>''):
                if(pg==0):
                    respon='你最近的分享消息： \n\n'+respon
                else:
                    respon='你的分享消息 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop..没有分享消息\n\n'
                    
            return respon



    def getRT(self,page='p0'):
        '''
        Command: -r/-rt
        Return the timeline of ur friends' retweets
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p以查看指定页RT\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getRt2Me(pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
            
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'r',user)
            if(respon<>''):
                if(pg==0):
                    respon='最近好友的RT消息： \n\n'+respon
                else:
                    respon='好友的RT消息 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop.没有好友的RT消息\n\n'
                    
            return respon




    def getTL(self,page='p0'):      
        '''
        Command: -me/-me page
        Return the user timeline 
        '''       
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-me p1以查看指定页消息\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.user_timeline(pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
                  
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'tl',user)
            if(respon<>''):
                if(pg==0):
                    respon='最近你的消息更新： \n\n'+respon
                else:
                    respon='你的消息更新 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop...没有消息更新\n\n'
                    
            return respon





    def getHomeTL(self,page='p0'):
        '''
        Command: -home/-home page/-ho/-ho page
        Return the user timeline 
        '''  
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-home p1以查看指定页消息\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.home_timeline(0,pg)
                except:
                    pass
                if(statecode==200):
                    break
            
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
            
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'htl',user)
            if(respon<>''):
                if(pg==0):
                    respon='最近消息更新： \n\n'+respon
                else:
                    respon='消息更新 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop...没有消息更新\n\n'
                    
            return respon





    def getListTL(self,name,list,page='p0'):
        '''
        Command: -list name list /-list name list page
        Return the list timeline 
        ''' 
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            pg=self._parsePage(page)
            if(pg==-1):
                return '操作失败，请在翻页数字前加上字符p，如-list kavin_gray test p1以查看指定页消息\n\n'
            if(pg==-2):
                return '操作失败，请检查输入格式是否正确，稍后再试\n\n'
            
            url=name+'/lists/'+list
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.list_timeline(url,0,pg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，可能此群组被设为私密无法查看，请稍后再试\n\n'
            
            contents = simplejson.loads(tww.getContent())
            respon=''
            respon=self._formatMsg(contents,'lt',user)
            if(respon<>''):
                if(pg==0):
                    respon='最近群组更新： \n\n'+respon
                else:
                    respon='群组更新 (Page '+str(pg)+')： \n\n'+respon
            else:
                respon='Oop...没有群组更新\n\n'
                    
            return respon



    def getIList(self,page=''):
        '''
        Command: -mlist/-mt
        Return the list The user've created
        '''
        db_ser = DBService()
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            # get listcursor
            if(page.lower()=='next'):
                cr=user.mlistcursor[1].encode('utf-8')
            elif(page.lower()=='pre'):
                cr=user.mlistcursor[0].encode('utf-8')
            elif(page==''):
                cr='-1'              
            else:
                return '操作失败，-mlist后面只能跟next或pre格式查看翻页，详细说明请参考帮助\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getLists(user.name,cr)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'
             
            contents = simplejson.loads(tww.getContent())
            respon=''
            for content in reversed(contents['lists']):
                respon=respon+'*'+content['user']['screen_name'].encode('utf8')+' '
                respon=respon+content['slug'].encode('utf8')+'* : '
                respon=respon+'群组名: '+content['slug'].encode('utf8')+' '
                respon=respon+'ID: '+str(content['id'])+' '
                respon=respon+'成员数:'+str(content['member_count'])+' '
                respon=respon+'简介:'+content['description'].encode('utf8')+'\n\n'
                
            if(respon<>''):
                respon=respon.replace("&lt;","<")
                respon=respon.replace("&gt;",">")
                
                respon='你创建的群组： \n\n'+respon
                # setting the listcursor
                db_ser.setMListcursor(user,contents['previous_cursor_str'],contents['next_cursor_str'])
                
            else:
                respon='Oop.没有创建的群组\n\n'
                    
            return respon


    def getList(self,page=''):
        '''
        Command: -list/-lt
        Return the list The user've followed
        '''
        db_ser = DBService()
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            # get listcursor
            if(page.lower()=='next'):
                cr=user.listcursor[1].encode('utf-8')
            elif(page.lower()=='pre'):
                cr=user.listcursor[0].encode('utf-8')
            elif(page==''):
                cr='-1'
            else:
                return '操作失败，-list后面只能跟next或pre格式查看翻页，详细说明请参考帮助\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getSubscriptions(user.name,cr)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

            contents = simplejson.loads(tww.getContent())
            respon=''
            
            for content in reversed(contents['lists']):
                respon=respon+'*'+content['user']['screen_name'].encode('utf8')+' '
                respon=respon+content['slug'].encode('utf8')+'* : '
                respon=respon+'群组名: '+content['slug'].encode('utf8')+' '
                respon=respon+'ID: '+str(content['id'])+' '
                respon=respon+'创建者:'+content['user']['screen_name'].encode('utf8')+' '
                respon=respon+'成员数:'+str(content['member_count'])+' '
                respon=respon+'简介:'+content['description'].encode('utf8')+'\n\n'
                
            if(respon<>''):
                respon=respon.replace("&lt;","<")
                respon=respon.replace("&gt;",">")
                respon='你关注的群组： \n\n'+respon
                # setting the listcursor
                db_ser.setListcursor(user,contents['previous_cursor_str'],contents['next_cursor_str'])
            else:
                respon='Oop.你没有关注的群组\n\n'
                    
            return respon



    def getListed(self,page=''):
        '''
        Command: -listed/-ld
        Return the lists that following the user 
        '''
        db_ser = DBService()
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)

            # get listcursor
            if(page.lower()=='next'):
                cr=user.listedcursor[1].encode('utf-8')
            elif(page.lower()=='pre'):
                cr=user.listedcursor[0].encode('utf-8')
            elif(page==''):
                cr='-1'
            else:
                return '操作失败，-listed后面只能跟next或pre格式查看翻页，详细说明请参考帮助\n\n'
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.getMemberships(user.name,cr)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

            contents = simplejson.loads(tww.getContent())
            respon=''
            
            for content in reversed(contents['lists']):
                respon=respon+'*'+content['user']['screen_name'].encode('utf8')+' '
                respon=respon+content['slug'].encode('utf8')+'* : '
                respon=respon+'群组名: '+content['slug'].encode('utf8')+' '
                respon=respon+'ID: '+str(content['id'])+' '
                respon=respon+'创建者:'+content['user']['screen_name'].encode('utf8')+' '
                respon=respon+'成员数:'+str(content['member_count'])+' '
                respon=respon+'简介:'+content['description'].encode('utf8')+'\n\n'
                
            if(respon<>''):
                respon=respon.replace("&lt;","<")
                respon=respon.replace("&gt;",">")
                respon='关注你的群组： \n\n'+respon
                # setting the listcursor
                db_ser.setListedcursor(user,contents['previous_cursor_str'],contents['next_cursor_str'])
            else:
                respon='Oop.没有关注你的群组\n\n'
                    
            return respon




    def getMsg(self,msgid):
        '''
        Command: -@ msgid
        Return the info of the tweet
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.rtMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，请检查消息id号输入是否正确，稍后再试 ERROR:'+str(statecode)+'\n\n'

            content = simplejson.loads(tww.getContent())
            rex='<a href=.*?>(.*)</a>'
            respon='查询消息内容: *'+content['user']['screen_name'].encode('utf8')+': '
            respon=respon+content['text'].encode('utf8')+'*\n'
            
            # Attach info to the target tweet
            respon=respon+self._attachID(content) 
            respon=respon+'\n\n'

            # check for in reply status                
            in_reply=content['in_reply_to_status_id']
            count=0
            statecode=400
            # get the thread(lateset three tweets) for the tweet
            while(count<>3 and str(in_reply).lower()<>'none'):
                count+=1
                try:
                    statecode=tww.rtMsg(in_reply)
                except:
                    pass
                if(statecode==200):
                    reply_content = simplejson.loads(tww.getContent())       
                    respon=respon+'答复消息: '+reply_content['user']['screen_name'].encode('utf8')+': '
                    respon=respon+reply_content['text'].encode('utf8')                 
                    # Attach info to the tweet
                    respon=respon+'\n'+self._attachID(content) 
                    respon=respon+'\n\n'                       
                    in_reply=reply_content['in_reply_to_status_id']                  
                else:
                    break
                    
            return respon


        
    def delMsg(self,msgid='0'):
        '''
        Command: -del/-del msgid
        Delete the tweet
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:                   
                    if(msgid=='0'):
                        # -del command,get the lateset tweet's id
                        statecode=tww.user_timeline()                 
                    else:
                        # -del msgid
                        statecode=tww.delMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode==403):
                return '操作失败，此消息不是你所发，所以没有权限删除此消息\n\n'
            elif(statecode<>200):
                return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

            if(msgid<>'0'):
                return '消息已成功删除:)\n\n'
            else:              
                contents = simplejson.loads(tww.getContent())
                statecode=400 # init status code
                for times in range(retry):
                    try:
                        statecode=tww.delMsg(str(contents[0]['id']))
                    except:
                        pass
                    if(statecode==200):
                        return '消息已成功删除:)\n\n'

            return '操作连接失败，请稍后再试。ERROR:'+str(statecode)+'\n\n'

        

    def setFollow(self,name):
        '''
        Command: -fo name/-follow name
        Follow other user
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.follow(name)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                respon='操作连接失败，可能是服务器负载过大，或者此用户已经是你的好友了，请稍后再试\n\n'
            else:
                respon='操作成功,你已经成功关注'+name.encode('utf8')+' :)\n\n'
                
            return respon


    def setUnFollow(self,name):
        '''
        Command: -uf name/-unfollow name
        Unfollow other user
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.unfollow(name)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                respon='操作连接失败，可能是服务器负载过大，或者此用户不在你的关注者名单中，请稍后再试\n\n'
            else:
                respon='操作成功,你已经成功取消关注'+name.encode('utf8')+' :)\n\n'
                
            return respon



    def isFollow(self,name):
        '''
        Command: -if name
        Check if other user is following u
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    if(tww.is_following(name)==True):
                        statecode=200
                        respon=name.encode('utf8')+' 已经在关注你\n\n'
                        break
                    elif(tww.is_following(name)==False):
                        statecode=200
                        respon=name.encode('utf8')+' 目前没有关注你\n\n'
                        break
                except:
                    pass
                
            if(statecode<>200):
                respon='操作失败，可能是服务器负载过大，或者是用户名有误，请稍后再试\n\n'
                
            return respon


        
    def setFav(self,msgid):
        '''
        Command: -fav msgid
        Set tweet to ur favorite
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.addFav(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作失败，可能是服务器负载过大，或者消息id号输入有误，请稍后再试\n\n'
            
            return '消息已成功分享:)\n\n'
                




    def setReply(self,msgid,tweet):
        '''
        Command: -@ msgid tweet
        Reply to a particular tweet
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            rex='.*?'+msgid+' (.*)'
            text=re.findall(rex,tweet)
            if(text==[]):
                return '操作失败，请检查回复格式是否正确，稍后再试\n\n'
            
            length=len(unicode(text[0].encode('utf8'),"utf8"))
            if(length>140):
                return '回复失败，当前字数个数为'+str(length)+'，已经超出140字的限制。\n\n'
            
            retry=3 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.rtMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作连接失败，可能是服务器负载过大，或者消息id号输入有误，请稍后再试\n\n'

            content = simplejson.loads(tww.getContent())
            msg="@"+content['user']['screen_name'].encode('utf8')+" "
            msg=msg+text[0].encode('utf8')
            
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.update(msg,msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode==200):
                return '回复成功:)\n\n'

            return '回复失败，稍后再试\n\n' 




    def setDM(self,name,tweet):
        '''
        Command: -d msgid tweet
        Set tweet to ur favorite
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            rex='.*?'+name+' (.*)'
            text=re.findall(rex,tweet)
            if(text==[]):
                return '操作失败，请检查私信格式是否正确，稍后再试\n\n'
            
            length=len(unicode(text[0].encode('utf8'),"utf8"))
            if(length>140):
                return '发送失败，当前字数个数为'+str(length)+'，已经超出140字的限制。\n\n'
            
            retry=3 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.sentDMessage(name,text[0].encode('utf8'))
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):              
                if(statecode==403):
                    respon='Oops....对方没有关注你，所以你无法直接私信给TA\n\n'
                else:
                    respon='操作连接失败，请检查用户名是否正确，请稍后再试\n\n'
            else:
                respon='私信发送成功:)\n\n'

            return respon
                





    def setRT(self,msgid,tweet=''):
        '''
        Command: -rt msgid tweet/-rt msgid
        Old Retweet
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            if(tweet<>''):
                rex='.*?'+msgid+' (.*)'
                text=re.findall(rex,tweet)
                if(text==[]):
                    return '操作失败，请检查RT格式是否正确，稍后再试'

            # get the content of tweet                
            retry=3 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.rtMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作失败，可能是服务器负载过大，或者ID号不正确，请稍后再试\n\n'

            content = simplejson.loads(tww.getContent())
            msg=''
            
            # attach comment to this tweet
            if(tweet<>''):
                msg=msg+text[0].encode('utf8')+' '
                
            msg=msg+"RT @"+content['user']['screen_name'].encode('utf8')+": "
            msg=msg+content['text'].encode('utf8')
            msg=msg+"\n\n"
            length=len(unicode(msg,"utf8"))
            if(length>140):
                return '发送失败，当前字数个数为'+str(length)+'，已经超出140字的限制。\n\n'
            
            statecode=400               
            for times in range(retry):
                try:
                    statecode=tww.update(msg)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作失败，可能是服务器负载过大，请稍后再试\n\n'

            return 'RT操作成功:)'
                    



    def setNewRT(self,msgid):
        '''
        Command: -r msgid
        New Retweet
        '''
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=3 # set the retry times
            statecode=400 # init status code
            
            for times in range(retry):
                try:
                    statecode=tww.rtMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '操作失败，可能是服务器负载过大，或者ID号不正确，请稍后再试\n\n'

            content = simplejson.loads(tww.getContent())
            
            if(content.has_key('retweeted_status')):                   
                msgid=str(content['retweeted_status']['id'])
                
            statecode=400
            for times in range(retry):
                try:
                    statecode=tww.newRTMsg(msgid)
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                if(statecode==403):
                    respon='操作失败，此消息是自己所发或已被你RT过，请检查后再试\n\n'
                else:
                    respon='操作失败，可能是服务器负载过大，请稍后再试\n\n'
            else:
                respon='RT操作成功:)\n\n'
                
            return respon
                    



    def setTime(self,stime):
        '''
        Command: -time stime
        Set refresh rate
        '''
        db_ser = DBService()        
        for user in self._results:
            
            if(not stime.isdigit()):
                return '操作失败，请注意设定格式，-time后的分钟数只能是1至5的整数，不能出现其他字符或小数\n\n'
            
            settime=int(stime)
            if(settime<1 or settime>5):
                respon='操作失败，消息刷新时间只能取1到5分钟(包括5分钟)，且必须是整分钟数\n\n'
            else:
                db_ser.setTime(user,settime)
                respon='设置成功！消息刷新时间为'+str(settime)+'分钟:)\n\n'
                
            return respon




    def setOauth(self,actoken,actokense,add):
        '''
        Command: -v actoken actokense
        Bind to a new account
        '''
        
        tww = AppEngineTwitter()
        tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
        
        retry=2 # set the retry times
        statecode=400 # init status code
        db_ser = DBService(add)
        
        for times in range(retry):
            try:
                statecode=tww.verify()
            except:
                pass
            if(statecode==200):
                break
            
        if(statecode<>200):
            return '验证失败，请检查你的验证码和密钥是否正确，格式:-v 空格 验证码 空格 密钥\n\n'
        else:
            db_ser.setQuery('TwiCount')
            twiNum=db_ser.getQuery()
            num=twiNum.count()
            tar=0 # it's a flag~
            if(num==0):
                # create counter
                db_ser.createCounter()
                # create user
                db_ser.createUser(1,tww,actoken,actokense)
                return '验证完成，已经成功绑定，您可以开始使用TwiTalker了， 输入-help查看帮助，同时建议您follow官方帐号Twi_Talker以了解最新消息和更新，Enjoy:)\n\n'

            for en in twiNum:
                twiCount=en.count
                if(twiCount>=250):
                    return '对不起，此帐号配额已满，请访问 http://twitalker.appspot.com/list 查看目前其他可注册的TwiTalker帐号\n\n'
                        
                # update counter
                cursor=1
                while(cursor<=10):
                    db_ser.setQuery(DATABASE[cursor])
                    point = db_ser.getQuery()
                    
                    if(point.count()<25):
                        # create user
                        db_ser.createUser(cursor,tww,actoken,actokense)
                        # update counter
                        db_ser.setCounter(en,twiCount+1)
                        return '验证完成，已经成功绑定，您可以开始使用TwiTalker了， 输入-help查看帮助，同时建议您follow官方帐号Twi_Talker以了解最新消息和更新，Enjoy:)\n\n'

                    cursor=cursor+1
                    
                if(cursor==11):
                    return '对不起，此帐号配额已满，请访问 http://twitalker.appspot.com/list 查看目前其他可注册的TwiTalker帐号\n\n'




    def updateOauth(self,actoken,actokense):
        '''
        Command: -v actoken actokense
        Update to a new account
        '''
        db_ser = DBService()
        
        for user in self._results:
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                        self.oauth_secret,
                        actoken,
                        actokense)
            
            retry=2 # set the retry times
            statecode=400 # init status code
            
            for times in range(retry):
                try:
                    statecode=tww.verify()
                except:
                    pass
                if(statecode==200):
                    break
                
            if(statecode<>200):
                return '验证失败，请检查你的验证码和密钥是否正确，格式:-v 空格 验证码 空格 密钥\n\n'

            try:
                db_ser.defaultUser(user,tww,actoken,actokense)
                return '更新验证完成，已经成功绑定新帐号:)\n\n'
            except:
                return '更新失败，请稍后再试\n\n'
                


        
    def updateUser(self):
        '''
        Command: -update
        '''
        db_ser = DBService()
        
        for user in self._results:
            
            actoken=user.actoken
            actokense=user.actokense
            tww = AppEngineTwitter()
            tww.set_oauth(self.oauth_key,
                    self.oauth_secret,
                    actoken,
                    actokense)
            
            retry=4 # set the retry times
            statecode=400 # init status code
            for times in range(retry):
                try:
                    statecode=tww.verify()
                    if(statecode==200):
                        break
                except:
                    pass
            if(statecode<>200):
                return '操作连接失败，可能是服务器负载过大，请稍后再试\n\n'

            content = simplejson.loads(tww.getContent())
            if(content['screen_name'].encode('utf-8').lower()==user.name.lower()):
                return '目前您的绑定信息不需要更新\n\n'
            db_ser.setName(user,content['screen_name'].encode('utf-8'))
            
            return '操作成功，已更新你的绑定信息:)\n\n'


        
    def removeUser(self):
        '''
        Command: -remove
        Remove the user from database
        '''
        db_ser = DBService()
        
        for user in self._results:
            db_ser.delUser(user)
            
        # update counter
        db_ser.setQuery('TwiCount')
        twiNum=db_ser.getQuery()
        for en in twiNum:
            try:
                db_ser.setCounter(en,en.count-1)
                return '设置成功！已经解除绑定，如需要再次使用TwiTalker请重新进行绑定认证，感谢使用TwiTalker:)\n\n'
            except:
                pass
        return '操作连接失败，可能是服务器负载过大，请稍后再试\n\n'





    # ============================================================
    #
    #     Methods for twi_handler and xmpp_handler
    #
    # ============================================================


    
    def recMsg(self,db_name):
        '''
        Receive tweets according to different mode
        '''
        # find the user from database
        db_ser = DBService()
        db_ser.setQuery(db_name)
        results = db_ser.getQuery()       
        retry_times=2  #set retry times
               
        for enty in results:
            
            # the user is online or not on off-mode
            if(enty.mode<>'off' and xmpp.get_presence(enty.email, self.bot_acount)):
                
                # loading and setting oauth...
                tww=AppEngineTwitter()
                tww.set_oauth(self.oauth_key,
                                self.oauth_secret,
                                enty.actoken,
                                enty.actokense)
                
                # time to receive tweet...
                if(enty.settime==enty.runtime):
                    
                    db_ser.setRuntime(enty,1)
                    
                    # == receive tweet ==                                     
                    # live-mode
                    statecode=400
                    if(enty.mode=='live'):                  
                        for tim in range(0,retry_times):
                            try:
                                #get list timeline
                                statecode=tww.list_timeline(enty.list,enty.msgid,-1) 
                            except: 
                                pass
                            if(statecode==200):
                                break
                            
                    # self-mode or on-mode        
                    else:                       
                        for tim in range(0,retry_times):
                            try:
                                #get hometimeline
                                statecode=tww.home_timeline(enty.msgid,-1) 
                            except: #sth go wrong...                     
                                pass
                            if(statecode==200):
                                break
                            
                    # == parsering tweets == 
                    if(statecode==200):                        
                        contents = simplejson.loads(tww.getContent())
                        if(contents<>[]):
                            #init and parse msgs
                            msg='' 
                            msg=self._parseMsg(contents,enty)                      
                            # send tweets to users..
                            if(msg<>''):
                                try:
                                    xmpp.send_message(enty.email,"\n"+msg)
                                except:
                                    continue                             
                            # update the latest msgid
                            db_ser.setMsgid(enty,contents[0]['id'])
                            
                    # == receive direct message ==
                    statecode=400
                    try:
                        statecode=tww.getDMessage(enty.dmid)
                    except: #sth go wrong...                     
                        pass
                    if(statecode==200):
                        
                        contents = simplejson.loads(tww.getContent())
                        if(contents<>[]):
                            msg='' #init msg
                            msg=self._parseDM(contents,enty)
                            
                            # send dm to users..
                            if(msg<>''):
                                try:
                                    xmpp.send_message(enty.email,"\n"+msg)
                                except:
                                    continue
                                
                            # update the latest msgid
                            db_ser.setDMid(enty,contents[0]['id'])
                            
                # when enty.settime <> enty.runtime...        
                else:
                    db_ser.setRuntime(enty,enty.runtime+1)
                              
            else: # off-mode or user not online...
                if(enty.msgid<>0):
                    db_ser.setMsgid(enty,0)




    def sentMsg(self,msg,add):
        '''
        Sending msg to update ur twitter
        '''
        db_ser=DBService(add)
        if(db_ser.isUser()):
            
            if(msg[0]=='-'):
                msg=msg[1:]
                
            length=len(unicode(msg,'utf-8'))
            if(length>140):
                return '发送失败，当前字数个数为'+str(length)+'，已经超出140字的限制。\n\n'

            results=db_ser.getQuery()            
            for user in results:
                
                actoken=user.actoken
                actokense=user.actokense
                tww = AppEngineTwitter()
                tww.set_oauth(self.oauth_key,
                        self.oauth_secret,
                        actoken,
                        actokense)
                
                retry=4 # set the retry times
                statecode=400 # init status code
                for times in range(retry):
                    try:
                        statecode=tww.update(msg)
                    except:
                        pass
                    if(statecode==200):
                        break
                    
                if(statecode<>200):
                    return '发送失败，可能是服务器负载过大，请稍后再试，错误代码:'+str(statecode)+'\n\n'
                else:
                    return '200'
        else:
            return UNBINDING_MSG



               




    # ======================================================================
    #
    #                     Private  Methods
    #
    # =====================================================================

    

    def _parseMsg(self,contents,enty):
        '''
        Parse messages from the contents of timeline
        '''
        respon=''
        rex='<a href=.*?>(.*)</a>'

        for content in reversed(contents):           
            msg=''           
            # the msg is not sent from you..
            if( content['user']['screen_name'] <> enty.name ):
                
                # =================  on/live mode   =================
                if(enty.mode=='on' or enty.mode=='live' ):             
                    msg='*'+content['user']['screen_name'].encode('utf8')+':* '                 
                    # bold the mentioned tweet      
                    if("@"+enty.name.lower() in content['text'].lower()):          
                        msg=msg+'*'+content['text'].encode('utf8').strip(' ')+'* '
                    else:
                        msg=msg+content['text'].encode('utf8')
                        
                    # Attach info of the tweet to each msg if id-mode is on.
                    if(enty.rt==True):                      
                        msg=msg+'\n'+self._attachID(content) 
                    msg=msg+'\n\n'
                    
                # =================     self mode    ===================    
                elif(enty.mode=='self'):
                    # receive mentioned tweet
                    if("@"+enty.name.lower() in content['text'].lower()): 
                        msg='*'+content['user']['screen_name'].encode('utf8')+":* "
                        msg=msg+content['text'].encode('utf8')
                        
                        # Attach info of the tweet to each msg if id-mode is on
                        if(enty.rt==True):                      
                            msg=msg+'\n'+self._attachID(content) 
                        msg=msg+'\n\n'

                respon=respon+msg # add msg to respon at the end of each circle

        if(respon<>''):
            respon=respon.replace("&lt;","<")
            respon=respon.replace("&gt;",">")
            
        return respon



    def _parseDM(self,contents,enty):
        '''
        Parse direct messages from the users' dm timeline
        '''
        respon=''
        
        for content in reversed(contents):
            msg="[私信] "+content['sender_screen_name'].encode('utf8')+": "
            msg=msg+content['text'].encode('utf8')
            msg='*'+msg.strip(' ')+'*'+'\n\n'                 # bold the dm
            respon=respon+msg # add msg to respon at the end of each circle

        if(respon<>''):
            respon=respon.replace("&lt;","<")
            respon=respon.replace("&gt;",">")
            
        return respon




    def _parsePage(self,page):
        
        if(page.isdigit()):
            return -1
        page=page.lower().replace('p','')
        if(page.isdigit()):
            return int(page)
        else:
            return -2



    def _formatMsg(self,contents,tar,user):
        
        respon=''
        rex='<a href=.*?>(.*)</a>'
        count=len(contents)
        
        for content in reversed(contents):
            
            if(tar=='dm'):
                msg='*'+str(count)+') '+content['sender_screen_name'].encode('utf8')+':* '
                msg=msg+content['text'].encode('utf8')
                
            else:
                msg='*'+str(count)+') '+content['user']['screen_name'].encode('utf8')+':* '
                if((tar=='fav' or tar=='htl' or tar=='r') and "@"+user.name.lower() in content['text'].lower()):
                    msg=msg+'*'+content['text'].encode('utf8').strip(' ')+'* '
                else:
                    msg=msg+content['text'].encode('utf8')  
                # attach info of the tweet
                if(user.rt==True): 
                    msg=msg+'\n'+self._attachID(content)  
                
            msg=msg+'\n\n'
            count=count-1
            respon=respon+msg
            
        if(respon<>''):
            respon=respon.replace("&lt;","<")
            respon=respon.replace("&gt;",">")
            
        return respon




    def _attachID(self,content):
        
        '''rex='<a href=.*?>(.*)</a>'
        
        respon='[ '+content['user']['name'].encode('utf8')+' 通过 '
        match=re.findall(rex,content['source'])
        if(match<>[]):
            respon=respon+match[0].encode('utf8')+' '
        else:
            respon=respon+'web '
        respon=respon+'| ID:  '+str(content['id']).encode('utf8')+' ]'''

        respon='[ ID:  '+str(content['id']).encode('utf8')+' ]'        
        
        return respon
        


